
import os
import pandas as pd
import tushare as ts
import time
# import datetime
from datetime import datetime, date,timedelta
import warnings
import numpy as np
import talib as tb
import re
import dxw
import other
import redis_db
from funcat import *
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

_1_, time_, _2_ = other.time_start()#start_time,today_time,today_hour=时间('20200731', '20200820', '16:12')
ts.set_token('b31e0ac207a5a45e0f7503aff25bf6bd929b88fe1d017a034ee0d530')
pro = ts.pro_api()
time_zhou6=int(pro.trade_cal(exchange='', start_date='20200101', end_date=time_).is_open[-1:])
# def V_predict(data):
#     """
#     当日成交量预测
#     1）根据时间计算今日时长
#     2）根据V*4/时长
#     3）
#     """
#     time_day_=time.localtime(time.time())
#     time_bili=time_day_.tm_hour-9.5+time_day_.tm_min/60
#     if 0<time_bili<=2:#上午九点半到11点半
#         time_day_time=time_bili
#     if 2<time_bili<=3.5:#中午11点半到1点
#         time_day_time=2
#     if 3.5<time_bili<=5.5:#下午一点到3点
#         time_day_time=time_bili-1.5
#     if 5.5<time_bili or time_bili<=0:#下午3点以后 #上午九点半前
#         time_day_time=4
#     time_day_timepass=round(4/time_day_time,2)
#     #print("现在时间{}:{},{}倍系数".format(time_day_.tm_hour,time_day_.tm_min,time_day_timepass))
#     data["volume_predict"]=data["volume"]*time_day_timepass
#     data["turnoverratio_predict"]=data["turnoverratio"]*time_day_timepass
#     data["amount_predict"]= data["amount"]*time_day_timepass
#     return data
def get_today_data():
    try:
        csv_data = pd.read_csv("db_temp/1.数据下载.txt", index_col=0)
        csv_data['code'] = csv_data['code'].astype(str).str.zfill(6)  # 1补缺
        csv_data = csv_data.loc[:, ~csv_data.columns.str.contains('^Unnamed')].drop_duplicates()  # 2去掉Unnamed 并且去重
        # csv_data = ts.get_today_all()  # 读取today实时数据
        # csv_data["liutongliang"] = csv_data["nmc"] / csv_data["trade"]
        # csv_data.to_csv("db_temp/1.数据下载.txt", encoding="utf-8")
        # print("保存数据到db_temp/1.数据下载.txt中,获取{}项".format(len(csv_data)))

    except:
        print("从db_temp/1.数据下载.txt中，读取数据")
        csv_data = pd.read_csv("db_temp/1.数据下载.txt", index_col=0)
        csv_data['code'] = csv_data['code'].astype(str).str.zfill(6)  # 1补缺
        csv_data = csv_data.loc[:, ~csv_data.columns.str.contains('^Unnamed')].drop_duplicates()  # 2去掉Unnamed 并且去重

    csv_data = csv_data[~csv_data.name.str.contains('ST')]  # 3洗掉ST
    csv_data = csv_data[~csv_data['open'].isin([0])]  # 4过滤开盘为0
    csv_data = csv_data[csv_data["trade"] < 45]  # 价格小于35
    csv_data = csv_data[csv_data["changepercent"] > -5]  # 5.删掉-3%以上的
    # csv_data=csv_data[(csv_data["amount"]>100000000)]
    # csv_data = csv_data[csv_data["turnoverratio"] > 1]  # 5.换手率大于2.5
    csv_data = csv_data.sort_values(by="turnoverratio", ascending=False)

    if time_zhou6 == 0:  # 周六==0,预测系数为1
        csv_data["volume_predict"] = csv_data["volume"]
        csv_data["turnoverratio_predict"] = csv_data["turnoverratio"]
    else:  # 平时进行预测
        csv_data =other.V_predict_data(csv_data)
        csv_data = csv_data[(csv_data["turnoverratio_predict"] >2) | (csv_data["volume_predict"] > 18000000)]  # 换手率大于3
    csv_data.to_csv("db_temp/{}筛选数据.txt".format(time_),encoding = "utf-8")
    print("db_temp/{}筛选数据.txt".format(time_))
    return csv_data
def dangri():
    data_ma=redis_db.today_vol_read(day=time_)
    data_ma=data_ma.dropna(axis=0, how='any')
    #print("读取完成",data_ma)
    data_ma['code'] = data_ma['code'].astype(int).astype(str).str.zfill(6)  # 1补缺
    data_ma= data_ma.loc[:, ~data_ma.columns.str.contains('^Unnamed')].drop_duplicates()  # 2去掉Unnamed 并且去重
    _a_=get_today_data()
    if len(_a_)==0:
        print("当日获取空集，todo")

    data_=pd.merge(_a_,data_ma,how='inner',on='code')

    # 2020.12.19增加第三种120不好，解决方法
    data_["vol_min"] = data_[["5日", "120日"]].min(axis=1)
    data_["vol_max"] = data_[["30日", "vol_min"]].max(axis=1)
    """
    5     |5      |30*  |30*      |120  |120
    30*   |120*   |5    |120      |30*  |5*
    120   |30     |120  |5        |5    |30
    第三种120不好，解决方法：和120比较，取大"""
    data_["vol_max2"] = data_[["120日", "vol_max"]].max(axis=1)
    data_ = data_[(data_["volume_predict"] > data_["vol_max2"]*1000000)|(data_["volume_predict"] > data_["120日"]*2000000)]
    data_.to_csv("db_temp/{}符合vp@vol_max条件数据有{}项.txt".format(time_,len(data_)),encoding = "utf-8")
    if len(data_)>1500:
        print("超涨了已经，寻找白马优势股票开始干，牛市来临")
    print(data_)
    t1=time.localtime()
    celve(df_hb=data_)
#_____________________________
def get_today_data_else():
    """
    1.读取股票dataframe（补全）
    2.for循环code
    :return:
    """
    df = pd.read_csv("db_temp/1.数据下载.txt", encoding="utf-8", index_col=0)
    df['code'] = df['code'].astype(int).astype(str).str.zfill(6)  # 1补缺
    df = df.loc[:, ~df.columns.str.contains('^Unnamed')].drop_duplicates()  # 2去掉Unnamed 并且去重

    len_data=int(len(df)/450+1)
    temp=pd.DataFrame()

    for i in range(len_data):
        ts_get_datalist=df[450*i:450*(i+1)].code.tolist()
        _df = ts.get_realtime_quotes(ts_get_datalist)                   #Single stock symbol
        _df=_df[['code','open','price','low','high','pre_close','volume','time']]

        temp=pd.concat([temp,_df])

    ts_get_data=temp.reset_index(drop=True)#重建索引
    #obj格式变成float
    ts_get_data['open'] = pd.to_numeric(ts_get_data['open'])
    ts_get_data['low'] = pd.to_numeric(ts_get_data['low'])
    ts_get_data['trade'] = pd.to_numeric(ts_get_data['price'])
    ts_get_data['high'] = pd.to_numeric(ts_get_data['high'])
    ts_get_data['volume'] = pd.to_numeric(ts_get_data['volume'])
    ts_get_data['settlement'] = pd.to_numeric(ts_get_data['pre_close'])
    print(ts_get_data)
    return ts_get_data
def gu_zhengze_sz(code):
    global i_code_temp
    if re.match(r'^6.*',code):
        i_code_temp=code+'.SH'
    if re.match(r'^(0|3).*',code):
        i_code_temp=code+'.SZ'

    return i_code_temp

def len_fangzhi(start_time,today_time):
    time_= pro.daily(ts_code='000001.SZ', start_date=start_time, end_date=today_time)['trade_date']#20200304
    """ts_code trade_date  open  high   low  close  pre_close  change    pct_chg  vol        amount
    0  000001.SZ   20180718  8.75  8.85  8.69   8.70       8.72   -0.02       -0.23   525152.77   460697.377"""
    #print("{}到{}一共{}天".format(start_time,today_time,len(time_)))#两时间间距15天 #20211030到20211119一共14天
    return len(time_),time_[0],time_[1]
def len_fangzhi_szcode(szcode,start_time,today_time):
    time_= pro.daily(ts_code=szcode, start_date=start_time, end_date=today_time)['trade_date']#20200304
    """ts_code trade_date  open  high   low  close  pre_close  change    pct_chg  vol        amount
    0  000001.SZ   20180718  8.75  8.85  8.69   8.70       8.72   -0.02       -0.23   525152.77   460697.377"""
    return len(time_)
def time_jg():
    """len_fangzhi(start_time,today_time) 函数+ fc_get(code,start_time,time_0,time_1):部分函数"""
    len_time,time_0,time_1=len_fangzhi(_1_, time_)
    if str(datetime.now())[11:13]<=str(15):
        time_t=time_0
    else:
        time_t=time_1
    #print(str(datetime.now())[11:13]==time_t) #False
    print("fc时间",time_t)#fc时间 20200408
    return time_t,len_time
#_____________________________
def celve(df_hb):
    n=0
    global funcat_time_t
    funcat_time_t, len_time = time_jg()  # 20200403 ,防止时间内没数据
    len_time, time_0, time_1=len_fangzhi(_1_, time_)
    for i_code in df_hb.code:
        if re.match(r'^(8).*', i_code):
            continue
        if re.match(r'^(4).*', i_code):
            continue
        # 防搬，正则
        szcode = gu_zhengze_sz(i_code)
        len_time_sz = len_fangzhi_szcode(szcode,_1_, time_)
        if len_time_sz <= len_time - 1:  # 防止出错
            #print(szcode,"___________________________")
            continue

        print(len_time_sz ,len_time)
        #print(i_code,"celve")
        # _today_price = df_hb.loc[df_hb['code'] ==i_code, 'trade']
        # _today_high = df_hb.loc[df_hb['code'] ==i_code, 'high']
        # _today_open = df_hb.loc[df_hb['code'] ==i_code, 'open']
        # _today_low = df_hb.loc[df_hb['code'] ==i_code, 'low']
        # _today_settlement = df_hb.loc[df_hb['code'] ==i_code, 'settlement']
        # _today_v = df_hb.loc[df_hb['code'] ==i_code, 'volume']
        # _today_vp = df_hb.loc[df_hb['code'] ==i_code, "volume_predict"]
        # _today_tp = df_hb.loc[df_hb['code'] ==i_code, "turnoverratio_predict"]
        #
        # if len((_today_price-_today_settlement).values)>1: #float64 2会出错，1才是对的,去掉读取不对的（很重要）
        #     continue
        # global today_price,today_high,today_open,today_low,today_settlement,today_v,today_vp,today_tp
        #
        # today_price = _today_price.item()
        # today_high =_today_high.item()
        # today_open = _today_open.item()
        # today_low = _today_low.item()
        # today_settlement =_today_settlement.item()
        # today_v =_today_v.item()
        # today_vp=_today_vp.item()
        # today_tp=_today_tp.item()
        # # 周线判断
        #
        # """还可在周末进行变换， 60轴线/5 >每日"""
        # try:
        #     df_w = ts.get_hist_data('{}'.format(i_code), ktype='W')[:130]  # 获取周k线数据
        #     df_w = df_w[::-1]  # 进行反转
        #     # df_w['30min_c_ma50'] = df_w.volume.rolling(window=120).mean()
        #     df_w['w_ma60'] = tb.MA(np.array(df_w.volume), timeperiod=60)
        #     df_w_shangzhou = (
        #     df_w[len(df_w) - 2:len(df_w) - 1]["volume"] > df_w[len(df_w) - 2:len(df_w) - 1]['w_ma60']).item()
        #     df_w_benzhou = today_vp > (df_w[len(df_w) - 2:len(df_w) - 1]['w_ma60']).item() / 4
        #
        # except:
        #     df_w_shangzhou,df_w_benzhou=False,False
        #
        # if df_w_shangzhou or df_w_benzhou:  # 周线成交量大于60天均量线
        #     time.sleep(0.121)  # 2020.9.21增加
        #     n+=1
        #     print(n,"")
        xixi(code=i_code)

"""    ts_code    code        name      area     industry list_date dxw   renqi  \time  close_yestday          MA_5         MA_30        MA_120  \  H_10    L_10   MA_C_50       vol_min       vol_max      vol_max2 
0     000001.SZ  000001      平安银行   深圳       银行  19910403  NaN   102.0 \ fc时间20201225          18.04  7.791452e+07  8.574498e+07  1.278677e+08s \ 19.10   17.79   18.3974  7.791452e+07  8.574498e+07  1.278677e+08
1     000002.SZ  000002       万科A   深圳     全国地产  19910129  NaN   215.0 
"""
def xixi(code:str):
    print(code)
    S(code)
    T(funcat_time_t)
    #print(funcat_time_t)
    if DMI_1() >= DMI_1()[1] and H > H[2] and DMI_1() > 45:
        print("------------------good,还要看",code,DMI_1(),DMI_1()[1])
if __name__ == '__main__':
    dangri()
    dangri()